<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : '编辑'"
        />
        <div class="options">
          <el-button
            :loading="btnLoading"
            type="primary"
            @click="dataFormSubmit()"
            >保 存</el-button
          >
          <el-button :loading="btnLoading" @click="goBack">取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '100%' }"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          :label-width="labelWidth"
          label-position="right"
        >
          <template v-if="!loading">
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="名称" prop="fullName">
                <el-input
                  v-model="dataForm.fullName"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="编码" prop="enCode">
                <el-input
                  v-model="dataForm.enCode"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="模板类型" prop="templateType">
                <el-select
                  disabled
                  v-model="dataForm.templateType"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in templateTypeOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="消息场景" prop="messageSource">
                <McBusinessDialog
                  v-model="dataForm.messageSource"
                  :title="dataForm.messageSourceName"
                  @change="onMessageSourceChange"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="消息渠道" prop="messageType">
                <el-select
                  v-model="dataForm.messageType"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '100%' }"
                  @change="resetChildForm"
                >
                  <el-option
                    v-for="(item, index) in messageTypeOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.enCode"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="排序" prop="sortCode">
                <el-input-number
                  v-model="dataForm.sortCode"
                  placeholder="数字文本"
                  :min="0"
                  :step="1"
                  controls-position="right"
                  :style="{ width: '100%' }"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="状态" prop="enabledMark">
                <el-switch
                  v-model="dataForm.enabledMark"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="说明" prop="description">
                <el-input
                  v-model="dataForm.description"
                  placeholder="请输入"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <!-- 站内信 -->
              <FormSys
                v-if="['1'].includes(dataForm.messageType)"
                ref="FormSysRef"
                v-model="childForm"
                :labelWidth="labelWidth"
                :keywordList="keywordList"
              ></FormSys>
              <FormEmail
                v-if="['2', '4', '5', '8'].includes(dataForm.messageType)"
                ref="FormEmailRef"
                v-model="childForm"
                :labelWidth="labelWidth"
                :keywordList="keywordList"
              ></FormEmail>
              <FormSms
                v-if="['3'].includes(dataForm.messageType)"
                ref="FormSmsRef"
                v-model="childForm"
                :labelWidth="labelWidth"
                :keywordList="keywordList"
              ></FormSms>
              <FormWxxcx
                v-if="['6'].includes(dataForm.messageType)"
                ref="FormWxxcxRef"
                v-model="childForm"
                :labelWidth="labelWidth"
                :keywordList="keywordList"
              ></FormWxxcx>
              <FormWxgzh
                v-if="['7'].includes(dataForm.messageType)"
                ref="FormWxgzhRef"
                v-model="childForm"
                :labelWidth="labelWidth"
                :keywordList="keywordList"
              ></FormWxgzh>
            </el-col>
          </template>
        </el-form>
      </el-row>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/message/api/mcMsgTemplate";
import McBusinessDialog from "@/views/message/mcBusiness/mcBusinessDialog.vue";
import FormSys from "./FormSys.vue";
import FormEmail from "./FormEmail.vue";
import FormWxgzh from "./FormWxgzh.vue";
import FormWxxcx from "./FormWxxcx.vue";
import FormSms from "./FormSms.vue";

export default {
  components: {
    McBusinessDialog,
    FormSys,
    FormEmail,
    FormWxgzh,
    FormWxxcx,
    FormSms,
  },
  props: [],
  data() {
    return {
      labelWidth: "100px",
      visible: false,
      loading: false,
      btnLoading: false,
      dataForm: {
        fullName: "",
        enCode: "",
        templateType: "",
        messageSource: "",
        messageSourceName: "",
        messageType: "",
        sortCode: 0,
        enabledMark: 1,
        description: "",
        title: "",
        content: "",
        templateCode: "",
        wxSkip: "",
        xcxAppId: "",
        subscriberType: "",
        fieldList: [],
      },
      childForm: {
        title: "",
        content: "",
        templateCode: "",
        wxSkip: "",
        xcxAppId: "",
        subscriberType: "",
        fieldList: [],
      },
      rules: {
        fullName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        enCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        // templateType: [
        //   {
        //     required: true,
        //     message: "请选择",
        //     trigger: "change",
        //   },
        // ],
        messageSource: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        messageType: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        enabledMark: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
      },
      templateTypeOptions: [
        { fullName: "自定义模板", id: "0" },
        { fullName: "系统模板", id: "1" },
      ],
      messageTypeOptions: [],

      keywordList: [],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getMessageTypeOptions();
  },
  mounted() {},
  methods: {
    resetChildForm() {
      this.childForm = {
        title: "",
        content: "",
        templateCode: "",
        wxSkip: "",
        xcxAppId: "",
        subscriberType: "",
        fieldList: [],
      };
    },
    /**消息场景change事件 */
    onMessageSourceChange(id, item) {
      if (!id) return (this.dataForm.messageSourceName = "");
      this.dataForm.messageSourceName = item.fullName;
      this.keywordList = item.keywordList;
    },
    getMessageTypeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "msgSendType",
        })
        .then((res) => {
          this.messageTypeOptions = res;
        });
    },
    goBack() {
      this.$emit("refresh");
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.$nextTick(() => {
              this.dataInfo(res.data);
              this.loading = false;
            });
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.enabledMark = 1;
          this.dataForm.templateType = "0";
          this.dataForm.sortCode = 0;
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          const _tp = this.dataForm.messageType;
          if (_tp === "1" && !this.$refs["FormSysRef"].submit()) return;
          if (
            ["2", "4", "5", "8"].includes(_tp) &&
            !this.$refs["FormEmailRef"].submit()
          ) {
            return;
          }
          if (_tp === "3" && !this.$refs["FormSmsRef"].submit()) return;
          if (_tp === "6" && !this.$refs["FormWxxcxRef"].submit()) return;
          if (_tp === "7" && !this.$refs["FormWxgzhRef"].submit()) return;

          this.dataForm = Object.assign({}, this.dataForm, this.childForm);
          var _data = this.dataList();
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.enabledMark = parseInt(_data.enabledMark);
      _data.deleteMark = parseInt(_data.deleteMark);
      for (let i = 0; i < _data.fieldList.length; i++) {
        var _list = _data.fieldList[i];
        _list.isTitle = _list.checked ? 1 : 0;
      }
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.enabledMark = parseInt(_dataAll.enabledMark);
      _dataAll.deleteMark = parseInt(_dataAll.deleteMark);
      this.keywordList = _dataAll.keywordList;
      for (let i = 0; i < _dataAll.fieldList.length; i++) {
        var _list = _dataAll.fieldList[i];
        this.$set(_list, "checked", _list.isTitle == 1 ? true : false);
        this.$set(_list, "keywordList", this.keywordList);
      }

      this.childForm = {
        title: _dataAll.title,
        content: _dataAll.content,
        templateCode: _dataAll.templateCode,
        wxSkip: _dataAll.wxSkip,
        xcxAppId: _dataAll.xcxAppId,
        subscriberType: _dataAll.subscriberType,
        fieldList: _dataAll.fieldList,
      };
      this.dataForm = _dataAll;
    },
  },
};
</script>
